package com.yq.master.controller;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yq.core.base.service.BaseService;
import com.yq.core.entity.SysRoleEntity;
import com.yq.core.service.SysPowerService;
import com.yq.core.service.SysRoleService;
import com.yq.core.util.Page;
import com.yq.core.util.Result;
import com.yq.master.annotation.AzerothAutowired;
import com.yq.master.bean.WebUserBean;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 信  息: [yinquan] [2017-03-04] [1.2];
 * 描  述: 信息状态返回类，同意使用此类返回数据
 */
@Controller
@RequestMapping(value = "/sys/role")
public class SysRoleController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(SysRoleController.class);

    //@AzerothAutowired
    //public SysPowerService sysPowerService;

    @AzerothAutowired
    public SysRoleService sysRoleService;

    protected BaseService getServcie() {
        return sysRoleService;
    }

    protected String getJumpData() {
        return "";
    }

    /*****************************************************************************************/
    /** 添加角色初始化 **/
    @RequestMapping(value = "insert",params="_m=init")
    public String insertInit(Model model, ServletRequest request) {
        return "sys/role/sys-role-insert";
    }

    /** 添加角色 **/
    @RequestMapping(value = "insert",params="_m=exec")
    @ResponseBody
    public Object insertExec(Model model, ServletRequest request) {
        super.fieldMap.clear();
        super.fieldMap.put("useStatus", "1");// 0禁用，1启用
        return super.insertExec(model, request);
    }

    /*****************************************************************************************/
    /** 编辑角色初始化 **/
    @RequestMapping(value = "update",params="_m=init")
    public String updateInit(Model model, ServletRequest request) {
        String uid = request.getParameter("uid");
        if(StringUtils.isNotBlank(uid)) {
            // 编辑初始化页面
            SysRoleEntity sysRoleEntity = sysRoleService.findUniqueById(uid);
            model.addAttribute("obj", sysRoleEntity);
        }
        return "sys/role/sys-role-update";
    }

    /** 编辑角色 **/
    @RequestMapping(value = "update",params="_m=exec")
    @ResponseBody
    public Object updateExec(Model model, ServletRequest request) {
        //super.fieldMap.clear();
        return super.updateExec(model, request);
    }

    /*****************************************************************************************/
    /** 删除角色 **/
    @RequestMapping(value = "delete",params="_m=exec")
    @ResponseBody
    public Object deleteExec(Model model, ServletRequest request) {
        super.fieldMap.clear();
        super.fieldMap.put("deleteStatus", "1");
        return super.updateExec(model, request);
    }

    /*****************************************************************************************/
    /** 角色搜索初始化 **/
    @RequestMapping(value = "search",params="_m=init")
    public String searchInit(Model model, ServletRequest request) {
        return "sys/role/sys-role-search";
    }

    /** 角色搜索 **/
    @RequestMapping(value = "search",params="_m=load")
    @ResponseBody
    public Object searchLoad(Model model, ServletRequest request) {

        Page page = super.getPage(request);

        String useStatus = request.getParameter("useStatus");
        Map<String, Object> parameters = Maps.newHashMap();

        if(StringUtils.isNotBlank(useStatus) && !useStatus.equals("-1")) {
            parameters.put("useStatus", useStatus);
        }

        page = sysRoleService.pageRoleList(parameters, page);
        return page;
    }

    /** 所有角色 **/
    @RequestMapping(value = "searchAll",params="_m=load")
    @ResponseBody
    public Object searchAllLoad(Model model, ServletRequest request) {

        String userUid = request.getParameter("userUid");
        String gain = request.getParameter("gain");
        Map<String, Object> parameters = Maps.newHashMap();

        if(StringUtils.isNotBlank(gain)) {
            parameters.put("gain", gain);
        }

        parameters.put("useStatus", "1");
        parameters.put("userUid", userUid);

        return sysRoleService.pageRoleAllList(parameters);
    }

    /*****************************************************************************************/
    /** 角色授权初始化 **/
    @RequestMapping(value = "accredit",params="_m=init")
    public String accreditInit(Model model, ServletRequest request) {
        String uid = request.getParameter("uid");
        model.addAttribute("roleUid", uid);
        return "sys/role/sys-accredit-update";
    }

    /*****************************************************************************************/
    /** 角色授权 **/
    @RequestMapping(value = "accredit",params="_m=exec")
    @ResponseBody
    public Object accreditExec(Model model, ServletRequest request) {

        Map<String, Object> parameters = Maps.newHashMap();
        Result result = isCheck(request);

        try{
            // 排序类型
            String powrUids = request.getParameter("powrUids");

            String roleUid = request.getParameter("roleUid");
            if(StringUtils.isBlank(roleUid)) {
                result.resoutError("角色标识不能为空");
                return result;
            }

            //WebUserBean webUserBean = super.getWebUserBean(request);

            parameters.put("powrUids", powrUids);
            parameters.put("roleUid", roleUid);

            sysRoleService.updateAccredit(parameters);

            result.resoutSucess("操作成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            result.resoutError("操作失败");
        }

        return result;
    }

    /*****************************************************************************************/
    /** 角色权限树 **/
    @RequestMapping(value = "accredit",params="_m=tree")
    @ResponseBody
    public Object accreditTree(Model model, ServletRequest request) {

        Map<String, Object> parameters = Maps.newHashMap();
        Map<String, Object> obj = Maps.newHashMap();
        List<Map<String, Object>> tree = Lists.newArrayList();

        parameters.put("roleUid", request.getParameter("roleUid"));
        List<Map<String, Object>> list = sysRoleService.rolePowerTree(parameters);

        for(Map<String, Object> m:list) {
            obj.put(m.get("id").toString(), m);
        }

        for (Map.Entry<String, Object> entry : obj.entrySet()) {
            // 获得当前对象
            Map<String, Object> power = (Map<String, Object>) entry.getValue();

            // 是否选中
            if(power.get("rp")!=null && power.get("funType").equals("3")) {
                power.put("checked", true);
            } else {
                power.put("checked", false);
            }

            if(power.get("parentUid")!=null) {
                // 获得父级
                Map<String, Object> parentPower = (Map<String, Object>) obj.get(power.get("parentUid"));
                List<Map<String, Object>> children = Lists.newArrayList();
                if(parentPower.get("children")!=null) {
                    children = (List<Map<String, Object>>) parentPower.get("children");
                }
                // 放入子类
                children.add(power);
                parentPower.put("children", children);
            } else {
                tree.add(power);
            }
        }
        return tree;
    }

    /*****************************************************************************************/
    /** 启用 **/
    @RequestMapping(value = "lock",params="_m=exec")
    @ResponseBody
    public Object lockExec(Model model, ServletRequest request) {
        return lockPower(request, "1");
    }

    /** 禁用 **/
    @RequestMapping(value = "unlock",params="_m=exec")
    @ResponseBody
    public Object unlockExec(Model model, ServletRequest request) {
        return lockPower(request, "0");
    }

    /*****************************************************************************************/
    /** 启用、禁用角色 **/
    private Object lockPower(ServletRequest request, String type) {
        Map<String, Object> parameters = Maps.newHashMap();
        Result result = isCheck(request);
        Date date = new Date();

        try {
            WebUserBean webUserBean = getWebUserBean(request);
            SysRoleEntity sysRoleEntity = sysRoleService.findUniqueById(getUid(request));
            sysRoleEntity.setUseStatus(type);
            sysRoleEntity.setUpdateBy(webUserBean.getUid());
            sysRoleEntity.setUpdateAt(date);

            sysRoleService.update(sysRoleEntity);

            result.resoutSucess("操作成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            result.resoutError("操作失败");
        }

        return result;
    }
}
